#include "UdpReceiverFileProject.h"
#include <QHostAddress>
#include <QNetworkDatagram>
#include <QFile>
#include <QDateTime>

UdpReceiverFileProject::UdpReceiverFileProject(QWidget *parent)
	: QWidget(parent)
	, ui(new Ui::UdpReceiverFileProjectClass)  // 初始化 UI 指针
	, udpSocket(new QUdpSocket(this))
	, serverRunning(false)
{
	ui->setupUi(this);  // 设置 UI

	connect(ui->startButton, &QPushButton::clicked, this, &UdpReceiverFileProject::onStartButtonClicked);
	connect(ui->stopButton, &QPushButton::clicked, this, &UdpReceiverFileProject::onStopButtonClicked);
	connect(udpSocket, &QUdpSocket::readyRead, this, &UdpReceiverFileProject::onReadyRead);
}

UdpReceiverFileProject::~UdpReceiverFileProject()
{
	stopServer();
	delete ui;  // 删除 UI 指针
}

void UdpReceiverFileProject::onStartButtonClicked()
{
	if (!serverRunning) {
		startServer();
	}
}

void UdpReceiverFileProject::onStopButtonClicked()
{
	if (serverRunning) {
		stopServer();
	}
}

void UdpReceiverFileProject::startServer()
{
	QString ip = ui->ipLineEdit->text();
	quint16 port = static_cast<quint16>(ui->portSpinBox->value());

	bool success = udpSocket->bind(QHostAddress(ip), port);

	if (success) {
		ui->statusLabel->setText("Server is running.");
		serverRunning = true;
	}
	else {
		ui->statusLabel->setText("Failed to start server.");
	}
}

void UdpReceiverFileProject::stopServer()
{
	udpSocket->close();
	ui->statusLabel->setText("Server is stopped.");
	serverRunning = false;
}

void UdpReceiverFileProject::onReadyRead()
{
	while (udpSocket->hasPendingDatagrams()) {
		QNetworkDatagram datagram = udpSocket->receiveDatagram();
		QByteArray data = datagram.data();

		// 生成唯一的文件名
		QString timestamp = QDateTime::currentDateTime().toString("yyyyMMdd_HHmmss_zzz");
		QString fileName = "received_file_" + timestamp;

		QFile file(fileName);
		if (file.open(QIODevice::WriteOnly)) {
			file.write(data);
			file.close();
			ui->statusLabel->setText("File received and saved as " + fileName);
		}
		else {
			ui->statusLabel->setText("Failed to save file.");
		}
	}
}
